var $;
layui.define(['form','xmSelect','common','upload'], function(exports){
	$ = layui.$;
	var setter = layui.setter
	,xmSelect = layui.xmSelect
	,common = layui.common
	,form = layui.form
	,upload = layui.upload;
	var parentJson = {};
   	$(window).resize(function() {
	   	var bodyC = $('.layui-card-body').css("height");
	   	var zhi = layui.common.PxConvertToNum(bodyC);
		$('.layui-own-border').css("height", zhi-90);
   	});
   	var obj = {
		setParentJson: function setParentJson(json){
			parentJson = json;
			load();
	   } 
   }
	upload.render({
		elem: '#imgUploadBtn'
		,url: layui.setter.host + '/upload/imagesOss'
		,accept: 'images'
		,multiple: true
		,acceptMime: 'image/*'
		   ,before: function(obj){
				layer.msg('图片上传中，请稍后', {
					  icon: 16
					  ,shade: 0.01
					});
		    }
		,done: function(res){
			layer.msg(res.msg);
			var val = $(this.item).prev("div").children("input").val();
			val = val==''?'':val+',';
			$(this.item).prev("div").children("input").val(val+res.src);
			imgSuoShow('imgUploadBtn',res.src);
		}
	});
   function load(){
	   	form.val('form1',{
			"userId":parentJson.userId
			,"username":parentJson.username
			,"name":parentJson.name
			,"phone":parentJson.phone
			,"photo":parentJson.photo
			}
		);		
	  form.render();
		$('.layui-btn').on('click', function(){
			var type = $(this).data('type');
			active[type] ? active[type].call(this) : '';
		});
		var active = {
			back: function(){
				backUrl();
			}
			,submit:function(){
				form.on('submit(save)', function(data){
					var field = data.field;
					layui.admin.req({
							url: layui.setter.host+'/adminmanager/user/update_photo'
							,type:'post'
							,dataType:'json'
							,contentType: "application/json; charset=utf-8"
							,data:JSON.stringify(field) 
							,done: function(res){
								if(res.status == setter.response.statusCode.status_Success){
									layer.msg(res.msg,{time:1000},function(){
										backUrl();
									});
								}else{
									layer.msg(res.msg);
								}
							}
						});
				});
				$('[lay-filter="save"]').trigger('click');
			}
		};
		function backUrl(){
			var bakUrl = parentJson.bakUrl;
			window.location.href = bakUrl;
		} 
   }
	//设置图片缩略图
	function imgSuoShow(buttonId,imgStr){
		var imgArray = imgStr.split(',');
		for (var i = 0; i < imgArray.length; i++) {
			if(imgArray[i] != ''){
				$('#'+buttonId).nextAll("div[imgshow]").append('<div class="imgbox">'
						+'<img class="layui-upload-img" imgHref src="'+ imgArray[i] +'">'
						+'<div class="closebox" onclick="deleteImg(this)"><img src="../../genius/layui/images/delete.png"></div>'
						+'</div>');
			}
		}
	}
	exports('edit', obj)
});
//获取删除oss文件的Key
function getKey(url) {
//	url = "http://youxian-shoutu.oss-cn-zhangjiakou.aliyuncs.com/1544850245369.png?Expires=1860210239&OSSAccessKeyId=LTAI67zMng4CyPb0&Signature=zuSxvJO1%2BsTbTBb8x1B4VwG5VWw%3D";
    var str = url.split("?")[0].substring(7);
    var ss = str.indexOf("/");
    return decodeURI(str.substring(ss + 1, str.length));

}

//删除Oss文件
function deleteImg(obj) {
    layer.msg('真的要删除吗？', {
        time: 0 //不自动关闭
        , btn: ['删除', '取消']
        , yes: function (index) {
            layer.close(index);
            //获取图片地址
            var imgUrl = $(obj).parent().find('.layui-upload-img').attr('src');
            var key = getKey(imgUrl);


            layui.admin.req({
                url: layui.setter.host + '/upload/ImgOssDelete'
                , type: 'post'
                , dataType: 'json'
                , contentType: "application/json; charset=utf-8"
                , data: JSON.stringify({'key': key})
                , done: function (res) {
                    //请求成功后
                    if (res.code == '0') {
                        //获取值的id
                        var inputId = $(obj).parent().parent().parent().find('input').attr('id');
                        //删除图片显示
                        $(obj).parent().remove();
                        var imgStr = '';
                        $('#' + inputId).parent().nextAll("div[imgshow]").find('.layui-upload-img').each(function (i, el) {
//							console.log($(el).attr('src'))
                            imgStr += $(el).attr('src') + ',';
                        });
                        if (imgStr.length >= 1) {
                            imgStr = imgStr.substring(0, imgStr.length - 1)
                        }
//						console.log(inputId)
//						console.log(imgStr.split(','))
                        $('#' + inputId).val(imgStr);
                        imgStr = null;
                    }
                    layer.msg(res.msg);
                }
            });
        }
    });

}
